package com.dd.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.dd.reggie.common.BaseContext;
import com.dd.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //2.定义不需要处理的'请求'路径(浏览器发出的路径与代码中路径不同)
    //若是静态资源本地代码中的页面不应拦截
    public String[] urls = new String[]{
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**",
            "/common/**",
            "/user/login",
            "/user/sendMsg"
    };

    //需要定义匹配器，如/backend/index.html与/backend/**匹配不上
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取本次请求url
        //获取当前url,使用request.getRequestURL()
        String requestURI = request.getRequestURI();
        log.info("拦截到请求{}",requestURI);

        //3.若不需要处理，直接放行
        if(matchURI(requestURI)){
            log.info("该请求不需处理：{}",requestURI);
            filterChain.doFilter(request,response);// 放行该跳转
            return;
        }

        //4-1.判断登录状态，若已登录直接放行
        if(request.getSession().getAttribute("employee") != null){
            log.info("用户已登录，id：{}",request.getSession().getAttribute("employee"));

            //将员工Id存储到线程中
            Long employeeId = (Long)request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(employeeId);

            filterChain.doFilter(request,response); // 放行该跳转
            return;
        }

        //4-1.判断移动端用户登录状态，若已登录直接放行
        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，id：{}",request.getSession().getAttribute("user"));

            //将员工Id存储到线程中
            Long userId = (Long)request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response); // 放行该跳转
            return;
        }


        //5.若未登录返回未登录结果，并且向客户端以输出流方式响应数据，即request.js中
        //if (res.data.code === 0 && res.data.msg === 'NOTLOGIN') { //返回登录页面

        log.info("用户未登录，拦截");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    public boolean matchURI(String requestURI){
        for (String url : urls) {
            /**
             * 注意match参数顺序不能反,所有的方法的参数都是一一对应，不能写错位置
             * public boolean match(
             *     String pattern,
             *     String path )
             */
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match) return true;
        }
        return false;
    }

}
